package com.hzhr.iot.collect.protocol.util;

import com.hzhr.iot.collect.dao.CachedCommandDao;
import com.hzhr.iot.collect.entity.CachedCommandEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CachedCommandUtil {
    @Autowired
    CachedCommandDao cachedCommandDao;

    public String getCachedCommand(String deviceId, String iotDeviceCode, String messageId) {
        List<CachedCommandEntity> cachedCommandEntityList = cachedCommandDao.selectListByDeviceId(deviceId);
        if (cachedCommandEntityList == null) return null;
        for (int i = 0; i < cachedCommandEntityList.size(); i++) {
            CachedCommandEntity cachedCommandEntity = cachedCommandEntityList.get(i);
            if (cachedCommandEntity.getMessageId().equals(iotDeviceCode + messageId)) {
                return cachedCommandEntity.getCommand();
            }
        }

        return null;
    }

    public void deleteCachedCommand(String deviceId, String iotDeviceCode, String messageId) {
        List<CachedCommandEntity> cachedCommandEntityList = cachedCommandDao.selectListByDeviceId(deviceId);
        if (cachedCommandEntityList == null) return;
        int j = -1;
        for (int i = 0; i < cachedCommandEntityList.size(); i++) {
            CachedCommandEntity cachedCommandEntity = cachedCommandEntityList.get(i);
            if (cachedCommandEntity.getMessageId().equals(iotDeviceCode + messageId)) {
                j = i;
                break;
            }
        }
        if (j != -1) {
            cachedCommandEntityList.remove(j);
        }

        if (cachedCommandEntityList.size() == 0) {
            cachedCommandDao.deleteByDeviceId(deviceId);
        } else {
            cachedCommandDao.setByDeviceId(cachedCommandEntityList, deviceId);
        }
    }
    public void deleteCachedCommand(String deviceId) {
        cachedCommandDao.deleteByDeviceId(deviceId);
    }
}
